package com.itheima.tlias84.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传到阿里云对象存储oss中的工具类
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public  class OssUtil {

    /**
     * MultipartFile spring封装的用于接收文件的对象
     * @param file
     * @return
     */
    public static String upload(MultipartFile file){
        //获取参数名
        log.info("name{}",file.getName());
        //拆分文件后缀名（类型）
        log.info("originalName{}",file.getOriginalFilename());
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        //阿里云oss访问路径
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填写Bucket名称，例如test-htovo
        String bucketName = "test-htovo";
        //生成不重复的id
        String uuid = UUID.randomUUID().toString();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName =uuid+suffix;
        //转移文件到阿里云oss
        // 创建OSSClient实例。要指定访问秘钥
        OSS ossClient = new OSSClientBuilder().build(endpoint,"LTAI5tJpTd8TXCtHN3hJx1dw"
                ,"zdHcagsCEreUaUw7X7Kc0KhDlgSVVp");
        try {
            ossClient.putObject(bucketName,objectName,file.getInputStream());
            String url = "https://"+bucketName+".oss-cn-hangzhou.aliyuncs.com/"+objectName;
             return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
